define(function (require, exports, module) {
    var template = require("template");
    var Ajax = require("ajax");
    var layer = require("layer");
    var util = require('util');
    require("laydate");
    
    var mediaObj = function (callback) {
        this.init.apply(this,arguments);
    };
    mediaObj.prototype = {
        constructor: mediaObj,
        options: {},
        init: function (options) {
            var t = this;
            t.options = $.extend({},t.options,options);
            $(".tipConNav").text("媒体舆情");
            $(window).off('scroll');
            $("#rightConBox").html(template("monitorMediaTemp",{}));
            t.mask();
            t.querySimilar();
            t.queryInformation();
            t.loadMediaList(1,"Monitoring/findMedia.do",null,null);
            t.isCollectionEvent();
            t.initDate();
        },
        mask: function(){
            $(".mask").css("height",$(document).height());
            $(".mask").css("width",$(document).width());
        },
        
        initDate:function(){
        	function getMoreDay(dateTemp, days) {  
        	    var dateTemp = dateTemp.split("/");  
        	    var nDate = new Date(dateTemp[1] + '/' + dateTemp[2] + '/' + dateTemp[0]); //转换为MM-DD-YYYY格式    
        	    var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);  
        	    var rDate = new Date(millSeconds);
        	    var currentDate = new Date();
        	    if(rDate.getTime()>currentDate.getTime()){ //endDate的最大时间设置为当前时间
        	    	rDate = currentDate;
        	    }
        	    var year = rDate.getFullYear();  
        	    var month = rDate.getMonth() + 1;  
        	    if (month < 10) month = "0" + month;  
        	    var date = rDate.getDate();  
        	    if (date < 10) date = "0" + date;  
        	    return (year + "/" + month + "/" + date);  
        	} 
        	function getLessDay(dateTemp, days) {  
        	    var dateTemp = dateTemp.split("/");  
        	    var nDate = new Date(dateTemp[1] + '/' + dateTemp[2] + '/' + dateTemp[0]); //转换为MM-DD-YYYY格式    
        	    var millSeconds = Math.abs(nDate) - (days * 24 * 60 * 60 * 1000);  
        	    var rDate = new Date(millSeconds);  
        	    var year = rDate.getFullYear();  
        	    var month = rDate.getMonth() + 1;  
        	    if (month < 10) month = "0" + month;  
        	    var date = rDate.getDate();  
        	    if (date < 10) date = "0" + date;  
        	    return (year + "/" + month + "/" + date);  
        	} 
        	var beginDate={
    		    elem: '#beginDate',
    		    max: laydate.now(),
    		    query: function(){
//    		    	console.log(222);
    		    },
    		    choose: function(datas){
    		    	datas=datas.replace(/-/g,'/');
                    endDate.min = datas; //开始日选好后，重置结束日的最小日期
                    endDate.start = datas //将结束日的初始值设定为开始日
                    endDate.max = getMoreDay(datas,30);
                },
                done: function(value, datas, endDate){
                	datas=datas.replace(/-/g,'/');
                	endDate.min = datas; //开始日选好后，重置结束日的最小日期
                    endDate.start = datas //将结束日的初始值设定为开始日
                    endDate.max = getMoreDay(datas,30);
                },
                reset: function (datas) {
                	datas=datas.replace(/-/g,'/');
                    endDate.min = '1900/01/01'; //重置结束日期的最小值
                    beginDate.start = laydate.now(); //将开始日期的初始值设定为今天
                },
    		};
        	var endDate={
    		    elem: '#endDate',
    		    max: laydate.now(),
    		    choose: function(datas){
    		    	datas=datas.replace(/-/g,'/');
    		    	beginDate.max = datas; //结束日选好后，重置开始日的最大日期
    		    	beginDate.min = getLessDay(datas,30);
                },
                done: function(value, datas, beginDate){
                	datas=datas.replace(/-/g,'/');
    		    	beginDate.max = datas; //结束日选好后，重置开始日的最大日期
    		    	beginDate.min = getLessDay(datas,30);
                },
                reset: function () {
                	beginDate.max = laydate.now(); //设置开始日期最大值
                    endDate.start = laydate.now(); //将结束日期的初始值设定为今天
                    beginDate.min = '1900/01/01';  //清空结束日后，重置开始日的最小时间
                },
    		};
        	//开始日期
            $("#beginDate").click(function(){
                laydate(beginDate);
            });
            
            //结束日期
            $("#endDate").click(function(){
                laydate(endDate);
            });
        },
        
        loadMediaList: function(pageIndex,url,beginDate,endDate) {
			var t = this;
    	    var bDate = new Date(beginDate); 
    	    var bDateVal = Math.abs(bDate);
    	    var bDates = new Date(bDateVal);
    	    var eDate = new Date(endDate); 
    	    var eDateVal = Math.abs(eDate);
    	    var eDates = new Date(eDateVal);
    	    if((beginDate && !endDate)||(!beginDate && endDate)||(bDates.getTime()>eDates.getTime())){
    	    	layer.msg('起止时间范围有误，请重新选择！');
            	return false;
    	    }
    	    if(eDates-bDates>2592000000){
    	    	layer.msg('时间范围仅限于一个月！');
            	return false;
    	    }
			
			Ajax.ajax({
				url: localhost + url,
				data: {
					pageIndex: pageIndex,
					articleType:"News",
					startDate: beginDate,
					endDate: endDate
				},
				beforeSend: function() {
					if(pageIndex==1){
						$('#media_table>tbody').html(template("loadingDom"));
					}else{
						$("#listDom").append("<div class='loadingMoreBox animated fadeIn nextloding'><span>正在加载中，请稍后</span></div>");
					}
				},
				success: function(data) {
    				//防止失效的请求影响到下次页面的滚动加载
    				var href = window.location.href.indexOf("admin/monitor_media");
    				if(href < 0 ) {
    					return;
    				}
					if(data.returnCode == 10000){
						if(data.returnData && data.returnData.length > 0) {
							$("#curBeginDate").val(beginDate);
							$("#curEndDate").val(endDate);
							$(".loadingBox").remove();
							$(".loadingMoreBox").remove();
							var tHead='',mediaList='',isCollection='',sourceName='',level='',colors='',colors_nature='',
								dataList = data.returnData;
							
							tHead = "<tr class='th'><th>标题</th><th>来源</th><th>作者</th><th>转载数</th><th>发布时间</th><th>性质</th><th>星级</th><th>收藏</th></tr>";
			                for (var i = 0; i < dataList.length; i++) {
			                    var item = dataList[i]; 
			                    //表格
			                    mediaList += '<tr data-id="'+ item.ifmId +'" class="'+ item.groupId +'" data-class="'+ item.groupId +'">';
			                    /*mediaList+='<td><i class="iconfont checkboxChange">&#xe6dc;</i><input data-id="'+ item.id +'" type="checkbox" class="checkItem"></td>';*/
			                    mediaList += '<td><a class="title" target="_blank" href="' + item.url + '">'+item.title+'</a></td>';
			                    
			                    if(item.articleType=="News"){
			                    	sourceName = item.websiteName;
			                    }else if(item.articleType=="Micro"){
			                    	sourceName = "微博";
			                    }else if(item.articleType=="BBS"){
			                    	sourceName = "论坛";
			                    }else if(item.articleType=="WeiXin"){
			                    	sourceName = "微信";
			                    }
			                    mediaList += '<td>'+sourceName+'</td>';
			                    mediaList += '<td>'+item.author+'</td>';
			                    if (item.reprintNumb <= 1) {
			                    	mediaList += '<td class="similar">无转载<ul class="similar_ul"></ul></td>';
			                    }else if(item.reprintNumb<100){
//			                        if(item.articleType == "Micro") {
//			                        	mediaList += '<td class="similar"><b>相似'+item.reprintNumb+'</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
//			                        } else {
//			                        	mediaList += '<td class="similar"><b>转载'+item.reprintNumb+'</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
//			                        }
			                    	mediaList += '<td class="similar"><b>转载'+item.reprintNumb+'</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
			                    }else {
			                    	mediaList += '<td class="similar"><b>转载99+</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
//			                        if(item.articleType == "Micro") {
//			                        	mediaList += '<td class="similar"><b>相似99+</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
//			                        } else {
//			                        	mediaList += '<td class="similar"><b>转载99+</b><div class="triangle_up"></div><ul class="similar_ul"></ul></td>';
//			                        }
			                    }
			                    mediaList += '<td>'+item.releaseTime+'</td>';
			                    if(item.nature=="正面"){
			                    	colors_nature="green";
			                    }else if(item.nature=="负面"){
			                    	colors_nature="red";
			                    }
			                    mediaList += '<td class="' + colors_nature +'">'+item.nature+'</td>';
			                    if(!item.starLevel){
			                    	level = "";
			                    }else{
			                    	level = item.starLevel;
			                    }
			                    mediaList += '<td>'+level+'</td>';
			                    
			                    if(item.isCollection==0){
			                    	isCollection = "收藏";
			                    	colors = "black";
			                    }else{
			                    	isCollection = "已收藏";
			                    	colors = "grey";
			                    }
			                    
			                    mediaList += '<td><a href="javascript:;" ';
			                    mediaList += isNull(item.isCollection,'data-isCollection=');
								mediaList += isNull(item.nature,'data-nature=');
								mediaList += isNull(item.ifmId,'data-ifmid=');
								mediaList += isNull(item.articleId,'data-articleid=');
								mediaList += isNull(sourceName,'data-articleType=');
								mediaList += isNull(item.author,'data-enshrineAuthor=');
								mediaList += isNull(item.title,'data-enshrineTitle=');
								mediaList += isNull(item.url,'data-enshrineUrl=');
								mediaList += isNull(item.releaseTime,'data-releaseTime1=');
								mediaList += isNull(level,'data-starLevel=');
								mediaList += isNull(item.reprintNumb,'data-reprintNum=');
								
			                    mediaList += ' class="collect '+ colors +'">'+isCollection+'</a></td>';
			                    mediaList += '</tr>';
			                }
			                
			                //如果属性值为空，那么此元素就不添加该属性
							function isNull(isText,data){
								if(isText||isText=='0'){
									var tL = data + "'"+isText+"'";
								}else{
									tL = '';
								}
								return tL;
							}
			                
			                if(pageIndex==1){
			                	$('#media_table>tbody').html('');
			                	$('#media_table>tbody').append(tHead+mediaList);
			                }else{
			                	$('#media_table>tbody').append(mediaList);
			                }
//			                util.CutOff();      //截断过长文字
			                if(href > -1 ) {
			                	t.loadPage(pageIndex,url,$('#beginDate').val(),$('#endDate').val());
			                }	
		
						} else {
							$(".loadingMoreBox").remove();
							$(window).off('scroll');
							if(pageIndex==1){
								$(".list_query").css("display","none");
								$('#media_table>tbody').html(template("noDataDom"));
							}
						}
					}
				}
			});
		},
		loadPage: function(pageIndex,url,beginDate,endDate) {
			var t = this;
			//获取页面顶部被卷起来的高度
			function scrollTop() {
				return Math.max(
					//chrome
					document.body.scrollTop,
					//firefox/IE
					document.documentElement.scrollTop);
			}
			//获取页面文档的总高度
			function documentHeight() {
				//现代浏览器（IE9+和其他浏览器）和IE8的document.body.scrollHeight和document.documentElement.scrollHeight都可以
				return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
			}
			function windowHeight() {
				return(document.compatMode == "CSS1Compat") ?
					document.documentElement.clientHeight :
					document.body.clientHeight;
			}
			if(window.location.href.indexOf("admin/monitor_media")>-1){
			}else{
				return false;
			}
			var isloading = false;
			$(window).off('scroll');
			$(window).on('scroll', function() {
				//判定是否加载中，防止重复加载
				if(!isloading){
					//滚动条卷起来的高度 + 窗口高度 >= 文档的总高度 - 50/*这里将滚动响应区域高度取50px*/；如果这个判断为true则表示滚动条滚动到了底部。
					if(scrollTop() + windowHeight() >= (documentHeight() - 50)) {
						isloading = false;
						pageIndex = parseInt(pageIndex)+ 1;
						$(window).off('scroll');
						if(window.location.href.indexOf("admin/monitor_media")>-1){
						}else{
							return false;
						}
						t.loadMediaList(pageIndex,url,beginDate,endDate);
						isloading = true;
					}
				}
			});
		},

        //查询相似信息
        querySimilar: function(){
            var count =0;
            $('#media_table>tbody').delegate('b','click',function(){
                if($(this).next().css('display') == 'none') {
                    count = 0;
                }else{
                	count = 1;
                }
                count++;
                if(count%2 ==0) { //关闭
                	$('.triangle_up').css('display','none');    //小三角
                    $('.similar_ul').css('display','none');    //隐藏其他弹框
                    return false;
                } else { //打开
                    $(this).next().next().empty();  //$(".similar_ul")
                    $(this).parents('tr').siblings().children().children('.triangle_up').css('display','none');    //小三角
                    $(this).parents('tr').siblings().children().children('ul').css('display','none');    //隐藏其他弹框
                    var ifmId = $(this).parents('tr').attr('data-id');
                    var groupId = $(this).parents('tr').attr('data-class');
                    var $this = $(this);
                    Ajax.ajax({
                        url: localhost + "Warning/findSimilarity.do",
                        type: 'post',
                        dataType: 'json',
                        data: {
                        	groupId: groupId, 
                        	ifmId: ifmId, 
                        	identifying:2, 
                        	articleType2:'News',
                        	startDate:$("#curBeginDate").val(),
                        	endDate:$("#curEndDate").val()
                        },
                        contentType : "application/x-www-form-urlencoded; charset=utf-8",
                        success: function (data) {
                            if(data.returnData.length>0) {
                            	var sourceNames='',mediaLists='';
                                for (var i =0;i< data.returnData.length; i++) {
                                    var dataSimilar = data.returnData[i];
    			                    
    			                    if(dataSimilar.articleType=="News"){
    			                    	sourceNames = dataSimilar.websiteName;
    			                    }else if(dataSimilar.articleType=="Micro"){
    			                    	sourceNames = "微博";
    			                    }else if(dataSimilar.articleType=="BBS"){
    			                    	sourceNames = "论坛";
    			                    }else if(dataSimilar.articleType=="WeiXin"){
    			                    	sourceNames = "微信";
    			                    }
                                    mediaLists = '<li class="similar_ul"><a class="similar_i" target="_blank" href="' + dataSimilar.url + '">' + dataSimilar.title+ 
                                    		   '</a><a href="javascript:void(0)" class="similar_i">'+ sourceNames +
                                    		   '</a><a href="javascript:void(0)" class="similar_i">'+ dataSimilar.author +
                                    		   '</a><a href="javascript:void(0)" class="similar_i">'+dataSimilar.releaseTime +'</a></li>';
                                    
                                    $this.next().next().append(mediaLists);
                                }
                                $this.parents('tr').css('position','relative');
                                $this.next().next().css('display','block');
                                $this.next().css('display','block');
                            }
                        }
                    });
                }
            });
            $('.body_monitor_media').click(function(e){
                if(e.target.className == 'similar_ul' || e.target.className == 'similar_i') {
                
                } else {
                    $('.triangle_up').css('display','none');
                    $('.similar_ul').css('display','none');
                }
            });
        },
        
        //方案查询
        queryInformation: function(){
            var t = this;
        	
            $('.searchBtn').on('click',function(){
        		//防止重复滚动加载数据
        		$(window).off('scroll');
        		t.loadMediaList(1,"Monitoring/findMedia.do",$('#beginDate').val(),$('#endDate').val());
        	});
        },
        
        //收藏
        isCollectionEvent: function(){
        	$('.monitor_table > tbody').delegate('.collect','click',function(){
        		$(this).removeClass('collect');
        		var t = $(this);
        		if($(this).attr("data-iscollection")==1){
        			return false;
        		}
        		var articleId = $(this).attr("data-articleid");
        		var ifmId = $(this).attr("data-ifmid");
        		var articleType = $(this).attr("data-articleType");
        		var enshrineAuthor = $(this).attr("data-enshrineAuthor");
        		var enshrineTitle = $(this).attr("data-enshrineTitle");
        		var enshrineUrl = $(this).attr("data-enshrineUrl");
        		var releaseTime1 = $(this).attr("data-releaseTime1");
        		var reprintNum = $(this).attr("data-reprintNum");
        		var params = {
        			articleId: articleId,
        			articleType: articleType,
        			enshrineAuthor: enshrineAuthor,
        			enshrineTitle: enshrineTitle,
        			enshrineUrl: enshrineUrl,
        			releaseTime1: releaseTime1,
        			ifmId: ifmId,
        			reprInt:reprintNum
        		}
    			Ajax.ajax({
    				url: localhost + "enshrine/insert.do",
    				data: params,
    				success: function(data) {
    					if(data.returnCode == 10000){
    						layer.msg(data.returnMessage,{time: 2000},function(){
    							t.attr("data-iscollection",1).text("已收藏").css({"color":"#7B8FA6","text-decoration":"none"});
    						});
    					} 
    				}
    			});
        	});
        }
    };
    module.exports = mediaObj;
});

